'use strict';
angular.module('gkwb')
    .factory('Student', ['$window', '$http', '$cacheFactory', '$q', function($window, $http, $cacheFactory, $q) {
        var cache = $cacheFactory('cache_student');
        return {
            get: function(examId) {
                var defered = $q.defer();
                var stu = cache.get('stu');
                if (!stu) {
                    $http.get('/api/students/' + examId)
                        .success(function(res) {
                            res.examId = examId;
                            defered.resolve(res);
                            cache.put('stu', res);
                        })
                        .error(function(err){
                            defered.reject(err);
                        })
                } else {
                    defered.resolve(stu);
                }
                return defered.promise;
            },
            getFromServer:function(examId){
                var defered = $q.defer();
                    $http.get('/api/students/' + examId)
                        .success(function(res) {
                            res.examId = examId;
                            defered.resolve(res);
                            cache.put('stu', res);
                        })
                        .error(function(err){
                            defered.reject(err);
                        })
                return defered.promise;
            },
            save:function(student){
                var defered = $q.defer();
                $http.post('/api/students',student)
                .success(function(res){
                    defered.resolve(res);
                })
                .error(function(err){
                    if(err)
                    defered.reject(err.message);
                })
                return defered.promise;
            },
            reset:function(){
                cache.remove('stu');
                var stu = cache.get('stu');
            }
        }
    }])
    .factory('Session', ['$window',function ($window) {
        var _sessionId = $window.sessionStorage.token;
        var _isReg = $window.sessionStorage.isSigned | false;
        return {
            getSessionId : function(){
                return _sessionId;
            },
            setSessionId : function(sessionId){
                _sessionId = sessionId;
            },
            isReg : function(){
                return _isReg;
            }
        };
    }])
    .factory('Pay', ['$http',function ($http) {
        
    
        return {
            isPaid:function(examId){
                return $http.get('/view/pay/paid?examId='+examId);
            }
        };
    }])